<template>
  <div class="map-monitor-rack-panel bg-white-6 absolute-top full-height">
    <MLayoutPage :loading="loading" bottomClass="no-padding" classes="bg-transparent" maxHeight="calc(100% - 1.25rem)"
                 topClass="no-padding">
      <template v-slot:top>
        <div class="bg-grey-1 text-body1 text-grey-9 q-pa-md">
          <div class="q-pb-sm">{{ $t('MapCore.MapRackMonitor') }}</div>
          <q-input v-model="filterText" :placeholder="$t('MapCore.FilterKeywords')" class="q-ml-lg" dense outlined
                   @keydown.enter="initData">
            <template v-slot:append>
              <q-icon name="search"></q-icon>
            </template>
          </q-input>
          <div class="row q-gutter-md q-pt-md">
            <q-btn color="primary" outline unelevated @click="handleBind('bind')">
              {{ $t('Binding') }}
            </q-btn>
            <q-btn outline text-color="primary" @click="handleSync">
              {{ $t('Misc.SynchronizeRCSData') }}
            </q-btn>
          </div>
        </div>
      </template>
      <template v-slot:default>
        <template v-for="row in rackList || []" :key="row.shelvesCode">
          <q-separator class="q-mx-sm q-my-xs"></q-separator>
          <q-item v-ripple class="rounded-borders bg-grey-2 text-black q-pa-sm" clickable @click.stop="handleRack(row)">
            <q-item-section class="text-grey-5 text-caption col-auto">
              <q-item-label class="row items-center justify-end">{{ `${$t('AGVCore.Brand')}` }}</q-item-label>
              <q-item-label class="row items-center justify-end">{{ `${$t('MapCore.Station')}` }}</q-item-label>
            </q-item-section>
            <q-item-section>
              <q-item-label class="row items-center">
                <qx-tooltip>{{ row.agvBrandCode }}</qx-tooltip>
              </q-item-label>
              <q-item-label class="row items-center">
                <qx-tooltip>{{ row.positionName }}</qx-tooltip>
              </q-item-label>
            </q-item-section>
            <q-item-section class="text-grey-5 text-caption col-auto">
              <q-item-label class="row items-center">{{ `${$t('CarrierCore.RackCode')}` }}</q-item-label>
            </q-item-section>
            <q-item-section>
              <q-item-label class="row items-center">
                <qx-tooltip>{{ row.shelvesCode }}</qx-tooltip>
              </q-item-label>
            </q-item-section>
            <q-item-section class="col-auto">
              <q-btn class="text-caption" dense flat padding=".25rem" text-color="primary"
                     @click.stop="handleUnbind(row)">
                {{ $t('Unbind') }}
              </q-btn>
            </q-item-section>
          </q-item>
        </template>
        <MEmpty v-if="!rackList?.length"></MEmpty>
      </template>
      <template v-if="!!rackList?.length" v-slot:bottom>
        <div class="q-gutter-x-sm bg-grey-1 q-pa-md row items-center justify-end">
          <span class="text-body1 q-pr-sm">{{ $t('Totals') }}: {{ pagination.rowsNumber || 0 }}</span>
          <q-pagination v-model="pagination.page" :max="maxPages" :max-pages="6" active-color="primary"
                        active-design="outline" color="grey-8" gutter=".5rem"
                        @update:model-value="initData()"></q-pagination>
        </div>
      </template>
    </MLayoutPage>
    <div class="map-monitor-shrink absolute bg-grey-2 row justify-center items-center cursor-pointer cursor-hover"
         @click.stop="handleShrink">
      <q-img :ratio="20/31" src="src/views/MapCore/MapGlobal/assets/Rack.png" width="1rem"></q-img>
      <q-tooltip anchor="bottom end" self="top left" v-bind="$tooltipAttr" v-bind:offset="[-25, 5]">
        <div class="text-no-wrap q-pa-xs">{{ $t('MapCore.MapRackMonitor') }}</div>
      </q-tooltip>
    </div>
  </div>
  <q-modal v-model="modalVisible" :header="$t('Binding')" :width="500" @beforeClose="beforeClose" @confirm="submitForm">
    <qx-form ref="FormRef" v-model="formInfo" :option="formOption"></qx-form>
  </q-modal>
  <q-modal v-model="syncModelVisible" :header="$t('Misc.SynchronizeRCSData')" width="400" @beforeClose="beforeClose"
           @confirm="submitForm">
    <qx-form ref="FormRef" v-model="formInfo" :option="syncOption"></qx-form>
  </q-modal>
</template>

<script setup>
import { i18n } from 'boot/i18n'
import { postAPI } from 'src/api'
import { getRemoteData } from 'src/enum/ajaxRemoteData.js'
import { createDialog, formatNumber } from 'src/utils/utils'
import { rackDirections, updateModes } from 'src/views/CarrierCore/enum.js'
import { exportAttrs } from 'src/views/MapCore/MapGlobal/utils/KonvaEvent.js'
import { handleSelectedPoints, zoomCanvasByFindPoint } from 'src/views/MapCore/MapGlobal/utils/MouseEvent.js'
import { searchPointByCoord } from 'src/views/MapCore/MapGlobal/utils/utils.js'
import { computed, ref, watch } from 'vue'

const props = defineProps({ mapGroundCode: { type: String, default: '' }, mapAlias: String })
const rackList = ref([])
const formInfo = ref({})
const FormRef = ref(null)
const expand = ref(false)
const AGVBrands = ref([])
const loading = ref(false)
const filterText = ref('')
const modalVisible = ref(false)
const syncModelVisible = ref(false)
const pagination = ref({ page: 1, rowsPerPage: 10, rowsNumber: 0, sortBy: '', descending: false })
const brandProps = computed(() => ({ label: 'agvBrandCode', value: 'agvBrandCode' }))
const maxPages = computed(() => Math.ceil(pagination.value.rowsNumber / (pagination.value.rowsPerPage || 1)) || 1)
const syncOption = computed(() => {
  return {
    span: 22, labelWidth: 90,
    column: [{
      label: `${i18n.t('AGVCore.AGVBrand')}`, field: 'agvBrandCode', type: 'select', options: AGVBrands.value,
      props: brandProps.value, required: true, change: updateBrandCode
    }]
  }
})
const formOption = computed(() => {
  return {
    span: 22, labelWidth: 100,
    column: [{
      label: `${i18n.t('AGVCore.AGVBrand')}`, field: 'agvBrandCode', type: 'select', options: AGVBrands.value,
      props: brandProps.value, required: true
    }, {
      label: `${i18n.t('CarrierCore.RackCode')}`, field: 'shelvesCode', required: true
    }, {
      label: `${i18n.t('CarrierCore.RackDirection')}`, field: 'shelvesDir', type: 'radio',
      options: rackDirections.value, value: '0'
    }, {
      label: `${i18n.t('MapCore.StationName')}`, field: 'pointCode', required: true
    }, {
      label: `${i18n.t('Misc.UpdateMode')}`, field: 'updateMode', type: 'radio', options: updateModes.value,
      value: '1'
    }]
  }
})
watch(expand, val => val && initData('clear'))
const initData = action => {
  if (action === 'clear') {
    rackList.value = []
    filterText.value = ''
    pagination.value.page = 1
  }
  const { mapGroundCode: newMapGroundCode } = props, params = { newMapGroundCode, keyword: filterText.value }
  params.pageNum = pagination.value.page
  params.pageSize = pagination.value.rowsPerPage
  loading.value = true
  postAPI('/yfagv/api/bindPointShelves/getBindPointShelvesByConverMapCode', params, data => {
    const { total, pageNum, list = [] } = data
    rackList.value = list
    pagination.value.page = +(pageNum || 1)
    pagination.value.rowsNumber = +(total || 0)
    loading.value = false
  }, () => (loading.value = false))
}
const updateBrandCode = (_, list = []) => (formInfo.value.mapShortName = list[0]?.mapCode)
const handleUnbind = row => {
  createDialog({ msg: `${i18n.t('MapCore.UnbindingTips')}` }, () => {
    postAPI('/yfagv/api/bindPointShelves/unBindPointShelves', row, () => initData())
  })
}
const handleBind = (action) => {
  if (!AGVBrands.value.length) {
    const { mapGroundCode } = props, params = { newMapGroundCode: mapGroundCode }
    getRemoteData(`${mapGroundCode}_agv_brand`, '/yfagv/api/agvCfgBrand/list', 'post', params)
      .then(data => (AGVBrands.value = data))
  }
  formInfo.value = { action }
  modalVisible.value = true
}
const handleSync = () => {
  const msg = `${i18n.t('Misc.SyncTip1')}`
  createDialog({ msg }, () => {
    if (!AGVBrands.value.length) {
      const { mapGroundCode } = props, params = { newMapGroundCode: mapGroundCode }
      getRemoteData(`${mapGroundCode}_agv_brand`, '/yfagv/api/agvCfgBrand/list', 'post', params)
        .then(data => (AGVBrands.value = data))
    }
    formInfo.value = {}
    syncModelVisible.value = true
  }, () => {})
}
const handleShrink = () => (expand.value = !expand.value)
const handleRack = row => {
  const { CANVAS, batchSelected } = exportAttrs(), pointLayers = CANVAS.find('.points')
  const x = formatNumber(row.positionX / 1000), y = formatNumber(row.positionY / 1000)
  const point = { position: () => ({ x, y }) }
  zoomCanvasByFindPoint(CANVAS, point, 300)
  const targetPoint = searchPointByCoord(pointLayers, `${x},${y}`)
  if (!targetPoint) return
  batchSelected.splice(0) && batchSelected.push(targetPoint)
  handleSelectedPoints(CANVAS, batchSelected)
}

const beforeClose = () => {
  if (FormRef.value) FormRef.value.onReset()
  modalVisible.value = false
  syncModelVisible.value = false
}
const submitForm = mDone => {
  FormRef.value.validate((form, done) => {
    const uri = form.action === 'bind' ? '/yfagv/api/bindPointShelves/bindPointShelves'
      : '/yfagv/api/bindPointShelves/refreshShelvesPointByMapShorNameFromRcs'
    postAPI(uri, form, () => {
      initData()
      done()
      mDone && mDone()
    }, () => {
      done()
      mDone && mDone(false)
    })
  }, () => mDone && mDone(false))
}
</script>
<style lang="scss" scoped>
.map-monitor-rack-panel {
  width: 20rem;
  left: v-bind('`${expand ? "0rem" : "-20rem"}`');
}

.q-item__label {
  min-height: 1.125rem;
}

.q-scrollarea {
  padding-bottom: 1.8rem;
}

.q-pagination:deep(.q-btn) {
  line-height: 1.2rem;
}

.map-monitor-shrink {
  top: calc(50% + 2.5rem);
  right: -1.35rem;
}
</style>